<?php

namespace app\index\controller;

use app\api\model\Member;
use think\facade\View;

class Index
{

    public function __construct()
    {
        $memberId = session('member_id');
        if (!empty($memberId)) {
            header('Location: /index/member/index/');
        }
    }

    public function index()
    {
        View::assign('name', 'zhangsan');
        View::assign('url', '<p>https://www.baidu.com/</p>');
        return View::fetch();
    }

    public function login()
    {
        $mobile = input('post.mobile');
        $password = input('post.password');
        $captcha = input('post.captcha');
        if (empty($mobile)) output_error('手机号码不能为空');
        if (empty($password)) output_error('密码不能为空');
        if (empty($captcha)) output_error('验证码不能为空');
        if (!captcha_check($captcha)) output_error('验证码不正确');
        //第二步：构造查询语句，向数据库发送查询的请求，如果构造条件成功地查询回数据
        $condition = array();
        $condition[] = ['member_mobile', '=', $mobile];
        $condition[] = ['member_password', '=', md5($password)];
        $data = Member::where($condition)->find();
        if (empty($data)) output_error('账号或密码错误');
        //第三步：检验成功之后，存储关键的session数据
        session('member_id', $data['member_id']);
        header('Content-Type: application/json; charset=UTF-8');
        $newData = array();
        $newData['code'] = 1;
        $newData['msg'] = 'success';
        $newData['data'] = '1';
        echo json_encode($newData);
    }

}
